package com.cksys.achievement.utils;

import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import java.time.Instant;

/**
 * @AUTHOR soft
 * @DATE 2019/1/2 23:47
 * @DESCRIBE
 */
@Component
public class CacheUtils {

    private CacheManager manager;

    public CacheUtils() {
        manager = CacheManager.create();
    }

    public void put(Object key, Object val, int ttl) {
        Element element = new Element(key, val, ttl * 60, 0);
        getCache().put(element);
    }

    public void put1(Object key, Object val) {
        put(key, val, 1); // 一分钟
    }

    public void put3(Object key, Object val) {
        put(key, val, 3); // 三分钟
    }

    public void put5(Object key, Object val) {
        put(key, val, 5); // 五分钟
    }

    public Object get(Object key) {
        Element element = getCache().get(key);
        if (element != null && !element.isExpired()) {
            return element.getObjectValue();
        }
        return null;
    }

    public boolean remove(Object key) {
        return getCache().remove(key);
    }

    private Ehcache getCache() {
        return manager.getCache("code");
    }

    /**
     * 获取一个随机key
     */
    public static String randomKey() {
        long second = Instant.now().getEpochSecond();
        Double v = Math.random() * 10000;
        String r = "" + second + v.intValue();
        return DigestUtils.md5DigestAsHex(r.getBytes());
    }

}
